package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.ResponseResult;
import com.vehiclemanagement.entity.InsuranceRecord;
import com.vehiclemanagement.service.InsuranceRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 车辆保险记录控制器
 */
@RestController
@RequestMapping("/insurance")
@Slf4j
public class InsuranceRecordController {

    @Autowired
    private InsuranceRecordService insuranceRecordService;

    /**
     * 分页查询保险记录
     */
    @GetMapping("/list")
    public ResponseResult<IPage<InsuranceRecord>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchTerm,
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Integer insuranceType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        IPage<InsuranceRecord> page = insuranceRecordService.pageInsurances(
                current, size, searchTerm, vehicleId, insuranceType, status, startTime, endTime);
        return ResponseResult.success(page);
    }

    /**
     * 获取保险记录详情
     */
    @GetMapping("/{id}")
    public ResponseResult<InsuranceRecord> getDetail(@PathVariable Long id) {
        InsuranceRecord insurance = insuranceRecordService.getInsuranceById(id);
        if (insurance == null) {
            return ResponseResult.fail("保险记录不存在");
        }
        return ResponseResult.success(insurance);
    }

    /**
     * 添加保险记录
     */
    @PostMapping
    public ResponseResult<Boolean> add(@RequestBody InsuranceRecord insurance) {
        // 参数验证
        if (insurance.getVehicleId() == null) {
            return ResponseResult.fail("车辆ID不能为空");
        }
        if (insurance.getInsuranceCompany() == null || insurance.getInsuranceCompany().trim().isEmpty()) {
            return ResponseResult.fail("保险公司不能为空");
        }
        if (insurance.getPolicyNumber() == null || insurance.getPolicyNumber().trim().isEmpty()) {
            return ResponseResult.fail("保单号不能为空");
        }
        if (insurance.getInsuranceType() == null) {
            return ResponseResult.fail("保险类型不能为空");
        }
        if (insurance.getStartTime() == null) {
            return ResponseResult.fail("保险生效时间不能为空");
        }
        if (insurance.getEndTime() == null) {
            return ResponseResult.fail("保险到期时间不能为空");
        }
        if (insurance.getPremium() == null || insurance.getPremium().compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseResult.fail("保费必须大于0");
        }

        boolean success = insuranceRecordService.addInsurance(insurance);
        return success ? ResponseResult.success(true, "添加保险记录成功") : ResponseResult.fail("添加保险记录失败");
    }

    /**
     * 更新保险记录
     */
    @PutMapping
    public ResponseResult<Boolean> update(@RequestBody InsuranceRecord insurance) {
        if (insurance.getId() == null) {
            return ResponseResult.fail("保险记录ID不能为空");
        }

        boolean success = insuranceRecordService.updateInsurance(insurance);
        return success ? ResponseResult.success(true, "更新保险记录成功") : ResponseResult.fail("更新保险记录失败");
    }

    /**
     * 删除保险记录
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> delete(@PathVariable Long id) {
        boolean success = insuranceRecordService.deleteInsurance(id);
        return success ? ResponseResult.success(true, "删除保险记录成功") : ResponseResult.fail("删除保险记录失败");
    }

    /**
     * 更新所有保险记录状态
     */
    @PutMapping("/update-status")
    public ResponseResult<Integer> updateAllStatus() {
        int count = insuranceRecordService.updateAllInsuranceStatus();
        return ResponseResult.success(count, "更新保险状态成功");
    }

    /**
     * 获取即将到期的保险记录
     */
    @GetMapping("/expiring")
    public ResponseResult<List<InsuranceRecord>> getExpiringInsurance(
            @RequestParam(required = false, defaultValue = "30") Integer days) {
        List<InsuranceRecord> list = insuranceRecordService.getExpiringInsurance(days);
        return ResponseResult.success(list);
    }

    /**
     * 获取已过期的保险记录
     */
    @GetMapping("/expired")
    public ResponseResult<List<InsuranceRecord>> getExpiredInsurance() {
        List<InsuranceRecord> list = insuranceRecordService.getExpiredInsurance();
        return ResponseResult.success(list);
    }

    /**
     * 增加理赔记录
     */
    @PutMapping("/claim/{id}")
    public ResponseResult<Boolean> addClaim(
            @PathVariable Long id,
            @RequestParam BigDecimal claimAmount) {
        if (claimAmount == null || claimAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseResult.fail("理赔金额必须大于0");
        }

        boolean success = insuranceRecordService.addClaim(id, claimAmount);
        return success ? ResponseResult.success(true, "增加理赔记录成功") : ResponseResult.fail("增加理赔记录失败");
    }

    /**
     * 统计某车辆的保险总保费
     */
    @GetMapping("/sum-premium/{vehicleId}")
    public ResponseResult<BigDecimal> sumPremium(@PathVariable Long vehicleId) {
        BigDecimal sum = insuranceRecordService.sumPremiumByVehicleId(vehicleId);
        return ResponseResult.success(sum);
    }

    /**
     * 统计某车辆的保险数量
     */
    @GetMapping("/count/{vehicleId}")
    public ResponseResult<Integer> countInsurance(@PathVariable Long vehicleId) {
        Integer count = insuranceRecordService.countInsuranceByVehicleId(vehicleId);
        return ResponseResult.success(count);
    }

    /**
     * 按保险类型统计
     */
    @GetMapping("/statistics/type")
    public ResponseResult<List<Map<String, Object>>> statisticsByType() {
        List<Map<String, Object>> result = insuranceRecordService.statisticsByType();
        return ResponseResult.success(result);
    }

    /**
     * 按年份统计
     */
    @GetMapping("/statistics/year")
    public ResponseResult<List<Map<String, Object>>> statisticsByYear() {
        List<Map<String, Object>> result = insuranceRecordService.statisticsByYear();
        return ResponseResult.success(result);
    }

    /**
     * 测试API是否正常
     */
    @GetMapping("/test")
    public ResponseResult<String> test() {
        return ResponseResult.success("保险记录API工作正常");
    }
} 